// 持久化管理
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'

const state = () => {
  return {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes // 侧边栏要使用的路由数据
  }
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  setRoutes(state, data) { // 设置侧边栏要使用的路由数据,拼接静态和动态路由
    state.routes = [...constantRoutes, ...data]
  }
}

const actions = {
  async login(context, data) {
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const data = await getUserInfo()
    context.commit('setUserInfo', data)
    return data
  },
  loginout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

